package com.bds.btcdc.snatch;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.bds.btcdc.http.HttpUtil;
import com.bds.btcdc.model.TPairConverter;
import org.apache.log4j.Logger;
import org.nutz.dao.Cnd;
import org.nutz.dao.impl.NutDao;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by DongChenchen on 2018/4/24 0024
 */
@Service
public class PairSnatch {
	private Logger LOGGER = org.apache.log4j.Logger.getLogger(getClass());
	@Resource
	private NutDao dao;

	/**
	 * 汇率查询
	 * nowapi  免费版 查询限制：50 次/小时
	 * @return
	 */
	public void getRealTimeValAndUpdate() {
		List<TPairConverter> lawerPairs = dao.query(TPairConverter.class, Cnd.where("lawerPair", "=", 1));
		for (TPairConverter pair : lawerPairs) {
			String pair_name = pair.getPair_name();
			//USDT和USD使用相同汇率
			pair_name=pair_name.toUpperCase().replace("USDT","USD");
			String[] pn = pair_name.split("/");
			if(pn.length!=2){
				continue;
			}
			String pn1=pair_name.toUpperCase().split("/")[0];
			String pn2=pair_name.toUpperCase().split("/")[1];
			//默认 1:1
			String[] pairs=new String[]{"QC","CNC"};
			if(Arrays.asList(pairs).contains(pn1)){
				pair.setReal_time_val(BigDecimal.ONE);
				pair.setRe_real_time_val(BigDecimal.ONE);
				pair.setReal_time(new Date());
				continue;
			}
			String main_url = "http://api.k780.com/?app=finance.rate&scur="+pn1
					+ "&tcur="+pn2+"&appkey=33108&sign=dbfc17b509a20e0066eca836051ffab8&format=json";
			String re_url = "http://api.k780.com/?app=finance.rate&scur="+pn2
					+ "&tcur="+pn1+"&appkey=33108&sign=dbfc17b509a20e0066eca836051ffab8&format=json";
			try {
				String result = HttpUtil.get(main_url);
				JSONObject json = JSONObject.parseObject(result);
				if("1".equals(json.getString("success"))) {
					pair.setReal_time_val(json.getJSONObject("result").getBigDecimal("rate"));
					pair.setReal_time(json.getJSONObject("result").getDate("update"));
				}else{
					LOGGER.info(json.getString("msg"));
				}
				String re= HttpUtil.get(re_url);
				JSONObject re_json = JSONObject.parseObject(re);
				if("1".equals(re_json.getString("success"))){
					pair.setRe_real_time_val(re_json.getJSONObject("result").getBigDecimal("rate"));
					pair.setReal_time(json.getJSONObject("result").getDate("update"));
				}else{
					LOGGER.info(json.getString("msg"));
				}


			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		int count = dao.update(lawerPairs);
		LOGGER.info("实时更新法币汇率的个数："+count);
	}

	/**
	 * 汇率查询
	 * 爬取https://finance.google.cn/
	 * 待改进
	 * @return
	 */
	public List<TPairConverter> spideRealTimeVal() {
		List<TPairConverter> lawerPairs = dao.query(TPairConverter.class, Cnd.where("lawerPair", "=", 1));
		for (TPairConverter pair : lawerPairs) {
			String main_url="https://finance.google.cn/finance/converter";
			String meta ="";
			try {
				String result = HttpUtil.get(main_url);
				String reg="name=meta value=(.*?)>";
				Matcher matcher = Pattern.compile(reg).matcher(result);
				if(matcher.find()) {
					meta = matcher.group(1);
					meta=meta.replace("&#61;","%3D");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			if(StringUtils.isNotEmpty(meta)){
				String url = "https://finance.google.cn/finance/converter?a=1&from=" +
						pair.getPair_name() + "&to=CNY&meta=" + meta;
				try {
					String result = HttpUtil.get(url);
					String regex = "class=\"bld\">(.*?)</";
					Matcher matcher = Pattern.compile(regex).matcher(result);
					if(matcher.find()) {
						String val = matcher.group(1);
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return null;

	}

}